/**
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-01-26 18:32:44
 * @Description  : 错题接口验证中间件
 */

const Joi = require('joi')
const { Op } = require('sequelize')
const R = require('@/models/Response')
const { ErrorQuestion } = require('@/models/model')
const {
  ERROR_SHARE_CODE,
  ERROR_SYSTEM_CODE,
  ERROR_USER_CODE
} = require('@/constants/errorCode')
const { IS_INTEGER, IS_UNSAFE_INTEGER } = require('@/constants/joiSchema')
const { dumpCheck: globalDumpCheck } = require('@/utils/dumpCheck')

const errorQuestionSchema = {
  errorQuestionIds: Joi.array().items(IS_UNSAFE_INTEGER),
  errorQuestionId: IS_UNSAFE_INTEGER,
  page: IS_INTEGER.min(1).default(1),
  pageSize: IS_INTEGER.min(1).default(999),
  name: Joi.string().min(1).max(255),
  paperId: IS_UNSAFE_INTEGER,
  examId: IS_UNSAFE_INTEGER,
  count: Joi.number()
}

const dumpCheck = {
  /**
   * @author: Hejh(3010733382@qq.com)
   * @description: 验证错题ID的合法性
   * @param {array<string>} errorQuestionIds 错题ID数组
   */
  checkErrorQuestionIds: async (errorQuestionIds) => {
    let newerrorQuestionIds = [...new Set(errorQuestionIds)]
    // 不能出现重复的
    if (newerrorQuestionIds.length !== errorQuestionIds.length) {
      return false
    }

    newerrorQuestionIds = newerrorQuestionIds.map((item) => BigInt(item))

    if (newerrorQuestionIds.length === 0) {
      return true
    }

    // 查看不重复的和数据库的是否对的上
    const myWhere = {
      id: {
        [Op.in]: newerrorQuestionIds
      }
    }
    const errorQuestions = await ErrorQuestion.findAll({
      where: myWhere
    })
    if (errorQuestions.length !== newerrorQuestionIds.length) {
      return false
    }

    return true
  }
}

/**
 * @description 错题列表查询的参数验证
 * @param {*} ctx
 * @param {*} next
 * @returns
 */
module.exports.listErrorQuestionValidate = async (ctx, next) => {
  const schema = Joi.object({
    page: errorQuestionSchema.page,
    pageSize: errorQuestionSchema.pageSize,
    paperId: errorQuestionSchema.paperId,
    userId: errorQuestionSchema.paperId,
    examId: errorQuestionSchema.examId
  }).validate(ctx.query)

  if (schema.error) {
    ctx.body = R.error(ERROR_SYSTEM_CODE.PARAMS_SCHEMA_ERROR)
    return
  }
  ctx.newQuery = schema.value
  await next()
}

module.exports.listPaperValidate = async (ctx, next) => {
  const schema = Joi.object({
    page: errorQuestionSchema.page,
    pageSize: errorQuestionSchema.pageSize,
    examId: errorQuestionSchema.examId.required()
  }).validate(ctx.query)

  if (schema.error) {
    ctx.body = R.error(ERROR_SYSTEM_CODE.PARAMS_SCHEMA_ERROR)
    return
  }
  ctx.newQuery = schema.value
  await next()
}

/**
 * @description 创建错题时的参数验证
 * @param {*} ctx
 * @param {*} next
 * @returns
 */
module.exports.createErrorQuestionValidate = async (ctx, next) => {
  const schema = Joi.object({
    questionId: errorQuestionSchema.errorQuestionId
  }).validate(ctx.request.body)

  if (schema.error) {
    ctx.body = R.error(ERROR_SYSTEM_CODE.PARAMS_SCHEMA_ERROR)
    return
  }
  const { questionId } = ctx.request.body
  // TODO 验证questionId的合法性
  const b4 = await globalDumpCheck.checkQuestionIds([questionId])
  if (!b4) {
    ctx.body = R.error(ERROR_USER_CODE.QUESTION_ID_ERROR)
    return
  }
  await next()
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 批量删除错题接口的参数验证
 * @param {*} ctx
 * @param {*} next
 */
module.exports.delErrorQuestionsValidate = async (ctx, next) => {
  const schema = Joi.object({
    errorQuestionIds: errorQuestionSchema.errorQuestionIds.required()
  }).validate(ctx.request.body)

  if (schema.error) {
    ctx.body = R.error(ERROR_SYSTEM_CODE.PARAMS_SCHEMA_ERROR)
    return
  }

  const { errorQuestionIds } = ctx.request.body

  // 验证错题ID数组的合法性
  const b4 = await dumpCheck.checkErrorQuestionIds(errorQuestionIds)
  if (!b4) {
    ctx.body = R.error(ERROR_SHARE_CODE.SHARE_ID_ERROR)
    return
  }
  await next()
}
